package com.ido.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * Create by zoub
 * Date 2025/4/23 3:08 PM
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OssClient {

    private final OssConfiguration ossConfiguration;
    private final OSS ossClient;

    /**
     * 上传文件
     *
     * @param file 文件
     * @param path 文件路径
     * @param size 限制文件大小
     * @return
     */
    public String upload(MultipartFile file, String path, Integer size) {
        // 文件判空
        if (Objects.isNull(file) || file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }
        // 限制文件上传大小
        if (size != null && file.getSize() > size * 1024 * 1024) {
            throw new RuntimeException("文件大小超出上传限制");
        }
        // 文件名字
        String fileName = getFileName(file);
        // 文件路径 img/202501/xxxx.jpg
        String dateTime = DateFormatUtils.format(new Date(), "yyyyMMddHHmmsssss");
        String local = path + "/" + dateTime.substring(0, 6) + "/" + fileName;
        String filePath = ossConfiguration.getDomain() + "/" + local;
        log.info("OSS upload filePath={}", filePath);
        try {
            PutObjectRequest request = new PutObjectRequest(ossConfiguration.getBucketName(), local, file.getInputStream());
            ossClient.putObject(request);
        } catch (Exception e) {
            log.info("OSS文件上传失败!，error={}", e.getMessage());
            throw new RuntimeException("文件上传失败");
        }
        // 替换url前缀，列如：替换cdn加速域名
        if (StringUtils.isNotBlank(ossConfiguration.getUrlPrefix())) {
            filePath = filePath.replace(ossConfiguration.getDomain(), ossConfiguration.getUrlPrefix());
        }
        return filePath;
    }

    private String getFileName(MultipartFile file) {
        // 获取文件名称
        String originalFilename = file.getOriginalFilename();
        // 文件名后缀
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        // 文件新名字
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return uuid + suffix;
    }


}
